﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RedHouse.Data.Entities;
using System.Text.RegularExpressions;
using RedHouse.Data.Common;
using RedHouse.Data.Base;

namespace RedHouse.AdminControl.UserControls.Account
{
    public partial class UCAccountDetail : System.Web.UI.UserControl
    {
        public string Message { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            Initialize();
            btnSave.Click += new EventHandler(btnSave_Click);
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            RedHouseUserAccount account = GetAccountFromView();
            string validateMessage = ValidateAccount(account);
            if (!string.IsNullOrEmpty(validateMessage))
            {
                ErrorPanel.Visible = true;
                Message = validateMessage;
            }
            else
            {
                OperationResult result = UserAccountService.Instance.SaveUserAccount(account);
                if (result.Result)
                {
                    SuccessPanel.Visible = true;
                }
                else
                {
                    ErrorPanel.Visible = true;
                    Message = result.Message;
                }
            }
        }

        private string ValidateAccount(RedHouseUserAccount account)
        {
            string validateMessage = string.Empty;
            string allowedCharsPattern = "^[a-z0-9]*$";
            if (!Regex.IsMatch(account.UserId, allowedCharsPattern, RegexOptions.IgnoreCase) || string.IsNullOrEmpty(account.UserId))
            {
                validateMessage = "Invalid UserId";
            }
            else if (!Regex.IsMatch(account.Password, allowedCharsPattern, RegexOptions.IgnoreCase) || string.IsNullOrEmpty(account.Password))
            {
                validateMessage = "Invalid Password";
            }
            return validateMessage;
        }

        private RedHouseUserAccount GetAccountFromView()
        {
            RedHouseUserAccount account = new RedHouseUserAccount()
            {
                UserId = txtUserId.Text,
                Password =txtPassword.Text,
                DisplayName = txtDisplayName.Text,
                CreatedBy = ((RedHouseUserAccount)Session["Account"]).UserId,
                CreatedDate = DateTime.Now
            };
           
            return account;
        }

        /// <summary>
        /// Initialize
        /// </summary>
        private void Initialize()
        {
            ErrorPanel.Visible = false;
            SuccessPanel.Visible = false;
        }
    }
}